package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.card.dao.BankDao;
import com.stlm2.dems.card.dao.CardDao;
import com.stlm2.dems.card.entity.Bank;
import com.stlm2.dems.card.entity.Card;
import com.stlm2.dems.dao.ConfigDao;
import com.stlm2.dems.entity.Config;
import com.stlm2.dems.dao.FmsFlowDao;
import com.stlm2.dems.entity.FlowSource;
import com.stlm2.dems.entity.FlowType;
import com.stlm2.dems.entity.FmsFlow;
import com.stlm2.dems.dao.MessagesDao;
import com.stlm2.dems.entity.Messages;
import com.stlm2.dems.sns.entity.Platform;
import com.stlm2.dems.sns.service.SmsService;
import com.stlm2.dems.entity.TiXianState;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.user.entity.AccountState;
import com.stlm2.dems.entity.User;
import com.stlm2.util.Memcached;
import com.stlm2.util.TiXianCode;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.entity.TiXianShenQing;
import com.stlm2.dems.dao.TiXianShenQingDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("tiXianShenQingService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class TiXianShenQingService extends BaseServiceImpl<TiXianShenQing> {

	@Resource
	private TiXianShenQingDao tiXianShenQingDao;
	@Resource
	private UserDao userDao;
	@Resource
	private CardDao cardDao;
	@Resource
	private AccountDao accountDao;
	@Resource
	private FmsFlowDao fmsFlowDao;
	@Resource
	private Memcached memcached;
	@Resource
	private MessagesDao messagesDao;
	@Resource
	private BankDao bankDao;
	@Resource
	private SmsService smsService;
	@Resource
	private ConfigDao configDao;

	@Override
	protected BaseDao <TiXianShenQing> getDao() {
		return tiXianShenQingDao;
	}
	/*
	*ZLQ
	*前台用户添加提现申请
    * token：
    * money：金额
    * password：交易密码
    * accountName：银行卡户名
    * bankid:开户银行ID
    * cardNum：银行卡卡号
    * factorage:手续费
    * kaihuhang:开户行
    * cardId:银行卡ID
	*
	 */
	public String addTiXianShenQing(ModelMap model,String token,String money,String password,String factorage,String cardId){
		Date date=new Date();
		Calendar cal = Calendar.getInstance();
		int week = cal.get(Calendar.DAY_OF_WEEK);
		if(week==7 || week==1){
			return   CodeContent.getModelByCode(0, "星期六，星期日不可兑换", model);
		}
		if(week==6){
			System.err.println(cal.get(Calendar.HOUR_OF_DAY));
			if(cal.get(Calendar.HOUR_OF_DAY)>17){
				return   CodeContent.getModelByCode(0, "星期五,18点以后不可兑换", model);
			}
		}
		if(StringUtils.isEmpty(money)){
			return   CodeContent.getModelByCode(0, "兑换积分不能为空", model);
		}
		if(Integer.parseInt(money)%100!=0){
			return   CodeContent.getModelByCode(0, "提现金额只能是100的倍数", model);
		}
		if(StringUtils.isEmpty(factorage)){
			return   CodeContent.getModelByCode(0, "服务费不能为空", model);
		}
		if(StringUtils.isEmpty(password)){
			return   CodeContent.getModelByCode(0, "密码不能为空", model);
		}
//		if(StringUtils.isEmpty(accountName)){
//			return   CodeContent.getModelByCode(0, "银行卡户名不能为空", model);
//		}
//		if(StringUtils.isEmpty(bankId)){
//			return   CodeContent.getModelByCode(0, "开户银行不能为空", model);
//		}
//		if(StringUtils.isEmpty(cardNum)){
//			return   CodeContent.getModelByCode(0, "银行卡号不能为空", model);
//		}
//		if(StringUtils.isEmpty(kaihuhang)){
//			return   CodeContent.getModelByCode(0, "开户行不能为空", model);
//		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		//防止重复提现
		Object o = memcached.get(loginUser.getId()+"tiXian");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"tiXian",10,"1");
		}
		Account account=accountDao.getByUserId(loginUser.getId());
		if(account==null){
			return   CodeContent.getModelByCode(0, "没有对应的积分账户", model);
		}
		if(account.getAccountState().equals(AccountState.Locked)){
			return   CodeContent.getModelByCode(0, "积分账户为锁定状态，不允许提现", model);
		}
		String password2 = account.getPassword();
		//判断密码是否正确
		if(password2==null || password2.equals("")){
			return CodeContent.getModelByCode(0,"未设置支付密码，请设置支付密码", model);
		}
		if (!password.equals(password2)) {
			return CodeContent.getModelByCode(0,"支付密码错误", model);
		}
		TiXianShenQing tiXianRecord= tiXianShenQingDao.getUserThisWeekRecord(loginUser.getId());
		if(tiXianRecord!=null){
			return   CodeContent.getModelByCode(0, "本周已经申请过，请下周再来", model);
		}
		BigDecimal tiXianMoney=new BigDecimal(money);//提现金额
		Config config=configDao.getByName("TIXIAN_FACTORAGE");
		if(config==null){
			return   CodeContent.getModelByCode(0, "获取手续费失败，请联系管理员", model);
		}
		BigDecimal tiXianFactorage=tiXianMoney.multiply(new BigDecimal(config.getConfigValue()));//手续费
		BigDecimal tiXianctualMoney=tiXianMoney.subtract(tiXianFactorage);//实际到账金额（提现金额 - 手续费）
		if(tiXianMoney.compareTo(new BigDecimal(100))==-1){
			return   CodeContent.getModelByCode(0, "兑换积分小于100，不能兑换", model);
		}
		if(new BigDecimal(tiXianMoney.intValue()).compareTo(tiXianMoney)!=0){
			return   CodeContent.getModelByCode(0, "兑换积分必须为整数", model);
		}
		if(tiXianFactorage.compareTo(new BigDecimal(factorage))!=0){
			//验证手续费是否正确
			return   CodeContent.getModelByCode(0, "服务费不正确", model);
		}
		BigDecimal residueMoney=account.getAccountMoney().subtract(tiXianMoney);//账户剩余金额：原始金额 — 提现金额
		if(residueMoney.compareTo(BigDecimal.ZERO)==-1){
			return   CodeContent.getModelByCode(0, "账户积分不足", model);
		}

		//添加兑换记录
		String tiXianCode= TiXianCode.generatorCode(loginUser.getId());
		Card userCard=cardDao.getById(Integer.parseInt(cardId));
		if(userCard==null){
			return CodeContent.getModelByCode(0, "银行卡ID不存在", model);
		}
		if(userCard.getCreateUserId()-loginUser.getId()!=0){
			return CodeContent.getModelByCode(0, "不是您名下关联的银行卡", model);
		}
		TiXianShenQing tiXianShenQing =new TiXianShenQing();
		tiXianShenQing.setState(TiXianState.Pending);
		tiXianShenQing.setUserId(loginUser.getId());
		tiXianShenQing.setCreateTime(new Date());
		tiXianShenQing.setMoney(tiXianMoney);
		tiXianShenQing.setCardId(userCard.getId());
		tiXianShenQing.setCode(tiXianCode);
		tiXianShenQing.setCardNum(userCard.getCardNum());
		tiXianShenQing.setAccountName(userCard.getAccountName());
		tiXianShenQing.setBankId(userCard.getBankId());
		tiXianShenQing.setFactorage(tiXianFactorage);
		tiXianShenQing.setActualMoney(tiXianctualMoney);
		tiXianShenQing.setKaihuhang(userCard.getKaihuhang());
		tiXianShenQingDao.add(tiXianShenQing);
		//修改资金账户
		account.setAccountMoney(residueMoney);
		accountDao.modify(account);
		//添加资金流水
		FmsFlow fmsFlow =new FmsFlow();
		fmsFlow.setType(FlowType.Reduce);
		fmsFlow.setSource(FlowSource.DuiHuan);
		fmsFlow.setChange_num(tiXianMoney);
		fmsFlow.setCreateTime(new Date());
		fmsFlow.setUserId(loginUser.getId());
		fmsFlow.setReferCode(tiXianCode);
		fmsFlowDao.add(fmsFlow);
		model.put("id",tiXianShenQing.getId());
		//用户提现记录 保存24小时
		JedisPool pool = null;
		Jedis jedis = null;
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
			Long time=new Date().getTime();
			String key="message:"+time+":"+tiXianShenQing.getUserId()+":tixianApply";
			jedis.set(key,tiXianShenQing.getMoney().toString());
			jedis.expire(key,86400);
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			pool.returnResource(jedis);
		}


		return  CodeContent.getModelByCode(1, "", model);
	}
	/*
	*前台用户获取资金的兑换记录列表
	* token:用户token
	* page:页码
	 */
	public String userGetTiXianShenQingList(ModelMap model,String token,String page){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		TiXianShenQing tiXianShenQing =new TiXianShenQing();
		tiXianShenQing.setUserId(loginUser.getId());
		pageview=tiXianShenQingDao.queryPageView(pageNo, pageSize,tiXianShenQing);
		return 	CodeContent.getModelByCode(1,"success", convert(pageview.getRecords()));
	}
	/*
*前台用户获取资金的兑换记录详情
* token:用户token
 */
	public String userGetTiXianShenQingDetails(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(StringUtils.isEmpty(id)){
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		TiXianShenQing tiXianShenQing=tiXianShenQingDao.getById(Integer.parseInt(id));
		return 	CodeContent.getModelByCode(1,"success", buildModel(tiXianShenQing));
	}
	/*zlq
	*获取资金的兑换记录列表
	 */
	public List<ModelMap> convert(List<TiXianShenQing> tiXianShenQings) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (tiXianShenQings != null && tiXianShenQings.size() > 0) {
			for (TiXianShenQing tiXianShenQing : tiXianShenQings) {
				ModelMap map = buildModel(tiXianShenQing);
				list.add(map);
			}
		}
		return list;
	}
	/*zlq
*获取资金的兑换记录列表
 */
	public ModelMap buildModel(TiXianShenQing tiXianShenQing) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ModelMap model = new ModelMap();
		model.put("id",tiXianShenQing.getId());
		model.put("createTime",formatter.format(tiXianShenQing.getCreateTime()));
		model.put("state",tiXianShenQing.getState().toString());
		model.put("stateValue",tiXianShenQing.getStateValue());
		model.put("code",tiXianShenQing.getCode());
		model.put("money",tiXianShenQing.getMoney());
		model.put("factorage",tiXianShenQing.getFactorage());
		User user=userDao.getById(tiXianShenQing.getUserId());
		model.put("userName",user.getName());
		Bank  bank=bankDao.getById(tiXianShenQing.getBankId());
		model.put("bankName",bank.getName());
		model.put("bankImg",bank.getImg()!= null ?bank.getImg(): "");
		model.put("accountName",tiXianShenQing.getAccountName());
		model.put("actualMoney",tiXianShenQing.getActualMoney());
		if(tiXianShenQing.getState().equals(TiXianState.Pending)){
			model.put("handTime","");
		}else {
			if(tiXianShenQing.getHandTime()!=null){
				model.put("handTime",formatter.format(tiXianShenQing.getHandTime()));
			}else {
				model.put("handTime","");
			}
		}
		if(tiXianShenQing.getCardNum()!=null){
			model.put("cardNum",tiXianShenQing.getCardNum().substring(tiXianShenQing.getCardNum().length()-4));
		}else {
			model.put("cardNum","");
		}



		return  model;
	}
	/*
*后台查询兑换记录列表
* token:用户token
* page:页码
* userName:用户名（用户登陆手机号）
* stateValue：状态值
* code:兑换记录编码
*
 */
	public String queryTiXianShenQingListCRM(ModelMap model,String token,String page,String userName,String stateValue,
										  String code){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		TiXianShenQing tiXianShenQing =new TiXianShenQing();
		if(NumberUtils.isDigits(userName)){
			User user=userDao.getByName(userName.trim());
			tiXianShenQing.setUserId(user.getId());
		}
		if(NumberUtils.isDigits(stateValue)){
			tiXianShenQing.setStateValue(Integer.parseInt(stateValue));
		}
		if(!StringUtils.isEmpty(code)){
			tiXianShenQing.setCode(code);
		}
		pageview=tiXianShenQingDao.queryPageView(pageNo, pageSize,tiXianShenQing);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convert(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();
	}
	/*
*后台查询兑换记录详情
* token:用户token
* id:兑换记录ID
 */
	public ModelMap getDetails(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			model.put("code",-1);
			model.put("msg","请登录");
			return model;
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			model.put("code",-1);
			model.put("msg","请登录");
			return model;
		}
		if(StringUtils.isEmpty(id)){
			model.put("code",0);
			model.put("msg","ID不能为空");
			return model;
		}
		TiXianShenQing tiXianShenQing=tiXianShenQingDao.getById(Integer.parseInt(id));
		model.put("datas",buildModelDetails(tiXianShenQing));
		model.put("code",1);
		model.put("msg","success");
		return model;
	}
	/*zlq
*后台查询兑换记录详情
*/
	public ModelMap buildModelDetails(TiXianShenQing tiXianShenQing) {
		ModelMap model = new ModelMap();
		if(tiXianShenQing!=null){
			//每周第一天为周日
			GregorianCalendar cal = new GregorianCalendar();
			int theWeek = cal.get(Calendar.WEEK_OF_YEAR);
//			System.out.println("本周是今年的第几周：" + theWeek);
			cal.setTime(tiXianShenQing.getCreateTime());
			int createWeek=cal.get(Calendar.WEEK_OF_YEAR);
//			System.out.println("创建时间是今年的第几周：" + createWeek);

			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			model.put("id",tiXianShenQing.getId());
			model.put("state",tiXianShenQing.getState().toString());
			model.put("stateValue",tiXianShenQing.getStateValue());
			User user=userDao.getById(tiXianShenQing.getUserId());
			model.put("userName",user.getName());
			model.put("createTime",formatter.format(tiXianShenQing.getCreateTime()));
			model.put("money",tiXianShenQing.getMoney());
			model.put("code",tiXianShenQing.getCode());
			if(tiXianShenQing.getNote()!=null){
				model.put("note",tiXianShenQing.getNote());
			}else {
				model.put("note","");
			}
			if(theWeek==createWeek){
				model.put("cardNum","********(本周记录不可查看)");
				model.put("isTheWeek",1);
			}else {
				model.put("cardNum",tiXianShenQing.getCardNum());
				model.put("isTheWeek",0);
			}
			model.put("accountName",tiXianShenQing.getAccountName());
			Bank  bank=bankDao.getById(tiXianShenQing.getBankId());
			model.put("bank",bank.getName());
			model.put("factorage",tiXianShenQing.getFactorage());
			model.put("actualMoney",tiXianShenQing.getActualMoney());
			model.put("kaihuhang",tiXianShenQing.getKaihuhang());
			if(!tiXianShenQing.getState().equals(TiXianState.Pending)){
				User handUser=userDao.getById(tiXianShenQing.getHandUserId());
				if(handUser!=null){
					model.put("handUserName",handUser.getName());
					model.put("handTime",formatter.format(tiXianShenQing.getHandTime()));
				}else {
					model.put("handUserName","");
					model.put("handTime","");
				}
			}else {
				model.put("handUserName","");
				model.put("handTime","");
			}


			
		}
		return  model;
	}

		/*
*后台审核兑换记录
* token:用户token
* id:兑换记录ID
* state:状态值 2：不通过 3 :通过
* note：备注
 */
	public String checkUpdateCRM(ModelMap model,String token,String id,String stateValue,String note){
		Messages messages =new Messages();
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(StringUtils.isEmpty(id)){
			return   CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		if(StringUtils.isEmpty(stateValue)){
			return   CodeContent.getModelByCode(0, "审批状态不能为空", model);
		}
		TiXianShenQing tiXianShenQing=tiXianShenQingDao.getById(Integer.parseInt(id));
		if(tiXianShenQing==null){
			return   CodeContent.getModelByCode(0, "没有找到记录", model);
		}
		if(!tiXianShenQing.getState().equals(TiXianState.Pending)){
			return   CodeContent.getModelByCode(0, "不是待审核状态，不能审核", model);
		}else {
			if(Integer.parseInt(stateValue)==TiXianState.Pass.getIntValue()){
				tiXianShenQing.setState(TiXianState.Pass);
			}else  if(Integer.parseInt(stateValue)==TiXianState.NoPass.getIntValue()){
				tiXianShenQing.setState(TiXianState.NoPass);
			}else {
				return   CodeContent.getModelByCode(0, "没有匹配的审核状态", model);
			}
			//每周第一天为周日
			GregorianCalendar cal = new GregorianCalendar();
			int theWeek = cal.get(Calendar.WEEK_OF_YEAR);
//			System.out.println("本周是今年的第几周：" + theWeek);
			cal.setTime(tiXianShenQing.getCreateTime());
			int createWeek=cal.get(Calendar.WEEK_OF_YEAR);
//			System.out.println("创建时间是今年的第几周：" + createWeek);
			if(theWeek==createWeek){
				return   CodeContent.getModelByCode(0, "本周记录不可审核", model);
			}
			//更新提现申请记录
			tiXianShenQing.setNote(note);
			tiXianShenQing.setHandTime(new Date());
			tiXianShenQing.setHandUserId(loginUser.getId());
			tiXianShenQingDao.modify(tiXianShenQing);
			//审核不通过
			if(tiXianShenQing.getState().equals(TiXianState.NoPass)){
				//添加资金流水
				FmsFlow fmsFlow =new FmsFlow();
				fmsFlow.setType(FlowType.Add);
				fmsFlow.setSource(FlowSource.DuiHuanNoPass);
				fmsFlow.setChange_num(tiXianShenQing.getMoney());
				fmsFlow.setCreateTime(new Date());
				fmsFlow.setUserId(tiXianShenQing.getUserId());
				fmsFlow.setReferCode(tiXianShenQing.getCode());
				fmsFlowDao.add(fmsFlow);
				//资金回放到用户账户
				Account account=accountDao.getByUserId(tiXianShenQing.getUserId());
				BigDecimal residueMoney=account.getAccountMoney().add(tiXianShenQing.getMoney());
				account.setAccountMoney(residueMoney);
				accountDao.modify(account);
				messages.setContent("您" + tiXianShenQing.getCode() + "的积分兑换订单:" + tiXianShenQing.getState().toString() + ",原因：" + tiXianShenQing.getNote() );
			}else {
				messages.setContent("您" + tiXianShenQing.getCode() + "的积分兑换订单:" + tiXianShenQing.getState().toString());
				//用户提现记录 保存24小时
				JedisPool pool = null;
				Jedis jedis = null;
				try {
					pool = RedisClient.getPool();
					jedis = pool.getResource();
					Long time=new Date().getTime();
					String key="message:"+time+":"+tiXianShenQing.getUserId()+":tixian";
					jedis.set(key,tiXianShenQing.getMoney().toString());
					jedis.expire(key,86400);
				}
				catch (Exception e){
					e.printStackTrace();
				}
				finally {
					pool.returnResource(jedis);
				}


			}
			messages.setTitle("积分兑换" + tiXianShenQing.getState().toString() );
			messages.setUserId(tiXianShenQing.getUserId());
			messages.setCreateTime(new Date());
			messages.setType(0);
			messages.setIfRead(false);
			messagesDao.add(messages);

			//发送短信通知
			User user=userDao.getById(tiXianShenQing.getUserId());
			String result=smsService.sendNotice(Platform.Wap,user,user.getName(),tiXianShenQing.getCode(),tiXianShenQing.getState());
			System.out.println(result);
		}
		return 	CodeContent.getModelByCode(1,"",model);
	}

	/*
*ZLQ
*获取提现手续费
*
 */
	public String getTiXianFactorage(ModelMap model){
		Config config=configDao.getByName("TIXIAN_FACTORAGE");
		if(config==null){
			return   CodeContent.getModelByCode(0, "获取手续费失败，请联系管理员", model);
		}

		List<String> remark=new ArrayList();
		remark.add("1、每周一次申请积分兑换的机会。（申请时间段为每周一至周五，周六日不可申请）");
		remark.add("2、兑换周期为一周时间。（即本周的兑换申请，系统会在下周一审核并兑换，节假日顺延）");
		remark.add("3、兑换额大于等于100且必须为整百可兑换");
		remark.add("4、兑换额转入银行卡收取"+ Double.parseDouble(config.getConfigValue())*100 + "%服务费");
		remark.add("5、如要更换银行卡，请到个人中心更改");
		model.put("serviceCharge",config.getConfigValue());
		model.put("remark", remark);
		model.put("code", 1);
		model.put("msg", "success");

		return new JSONObject(model).toString();
	}




}